<?php
// +----------------------------------------------------------------------
// | HkCms 基本配置模型
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\admin\model\routine;

use think\app\Url;
use think\facade\Validate;
use think\Model;

class Config extends Model
{
    /**
     * 配置写入缓存初始化
     * @param $clear true-清空，重新初始化
     */
    public static function initConfig($clear = false): array
    {
        if (true == $clear) {
            cache('site',NULL);
        }

        $Site = cache('site');
        if (empty($Site)) {
            $Site = [];

            $list = self::select()->toArray();
            foreach ($list as $k=>$v) {
                // 移除应用中心账号
                if ($v['name']=='cloud_username') {
                    cache('cloud_username', $v['value']);
                    continue;
                }
                if ($v['name']=='cloud_password') {
                    cache('cloud_password', $v['value']);
                    continue;
                }

                if (!empty($v['data_list'])) {
                    if ($v['type'] == 'radio' || $v['type'] == 'select') {
                        $Site[$v['name']] = $v['value'];
                    } else if ($v['type'] == 'checkbox' || $v['type'] == 'selects') {
                        $value = explode('|',$v['value']);
                        if (empty($value)) {
                            $Site[$v['name']] = [];
                        } else {
                            $Site[$v['name']] = $value;
                        }
                    }
                } else {
                    $Site[$v['name']] = $v['value'];
                }
                if ($v['name'] == 'file_size' || $v['name'] == 'chunk_size') {
                    $Site[$v['name']] = $v['value']*1024*1024;
                }
                if ($v['name'] == 'file_type') {
                    $Site[$v['name']] = str_replace('|',',',$v['value']);
                }
            }
            cache('site',$Site);
        }

        // 上传地址
        if (isset($Site['upload_url']) && !Validate::is($Site['upload_url'],'url')) {
            $Site['upload_url'] = request()->baseFile(true).$Site['upload_url'];
        }

        return $Site;
    }

    /**
     * 删除后的处理
     * @param Config $model
     * @throws \think\Exception
     */
    public static function onAfterDelete($model)
    {
        self::initConfig();
    }
}
